package com.by.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.by.biz.UsersBiz;
import com.by.entity.Users;
import com.by.util.Page;

@Controller
public class UsersController {
	@Resource
	private	UsersBiz	usersBiz;
	
	@RequestMapping(value="login", method=RequestMethod.GET)
	public	String	login(){
		return "login";
	}
	
	@RequestMapping(value="login", method=RequestMethod.POST)
	public	String	login(Users users, HttpSession session, Model model){
		Users loginUser = usersBiz.login(users);
		if(loginUser == null){
			model.addAttribute("msg", "用户名不存在");
			return "login";
		}
		if(!loginUser.getPassword().equals(users.getPassword())){
			model.addAttribute("msg", "用户名或密码错误");
			return "login";
		}
		if(loginUser.getStatus() == 0){
			model.addAttribute("msg", "该用户已冻结");
			return "login";
		}
		
		session.setAttribute("USERS", loginUser);
		return "redirect:index";
	}
	
	@RequestMapping(value="index", method=RequestMethod.GET)
	public	String	index(Model model){
		model.addAttribute("page", new Page<Users>());
		return "index";
	}
	
	@RequestMapping(value="findPage")
	public	String	findPage(Page<Users> page, Model model){
		if(page.getPageNo() == 0){
			page.setPageNo(1);
		}
		if(page.getCon() == null){
			page.setCon("");
		}
		page = usersBiz.findPage(page);
		model.addAttribute("page", page);
		return "index";
	}
	
	@RequestMapping(value="logout")
	public	String logout(HttpSession session){
		session.invalidate();
		return "login";
	}
	
	// 锟斤拷锟斤拷锟睫革拷锟斤拷锟斤拷锟斤拷锟�
	@RequestMapping(value="modifyPwd", method=RequestMethod.GET)
	public	String	modifyPwd(){
		return "modifyPwd";
	}
	
	@RequestMapping(value="modifyPwd", method=RequestMethod.POST)
	public	String	modifyPwd(@RequestParam("oldPwd") String oldPwd, 
								@RequestParam("newPwd") String newPwd, 
								@RequestParam("id")	Integer id,
								HttpSession session, Model model){
		Users users = (Users)session.getAttribute("USERS");
		if(users == null){
			return "login";
		}
		
		if(!users.getPassword().equals(oldPwd)){
			model.addAttribute("msg", "旧密码错误");
			return "modifyPwd";
		}
		
		users.setPassword(newPwd);
		usersBiz.update(users);
		
		model.addAttribute("msg", "修改成功");
		return "modifyPwd";
	}
}



















